<template>
    <div class="custom-tab-bar">
        <van-tabbar v-model="active" @change="onChange" inactive-color="#a6a6a6" active-color="#83cc2b" placeholder
            safe-area-inset-bottom>
            <van-tabbar-item v-for="(item, index) in list" :key="index" :to="shouldRoute(index) ? item.name : ''"
                replace>
                <span>{{ item.title }}</span>
                <template #icon="props">
                    <img :src="props.active ? item.active : item.normal" />
                </template>

                <div v-if="index === list.length / 2 - 1" class="circle-image-container">
                    <img src="@/assets/images/icon_middle.png" @click.stop="search" />
                </div>
            </van-tabbar-item>
        </van-tabbar>
    </div>
    <!-- 登录确认弹窗 -->
    <div v-if="showLoginConfirm" class="login-confirm-overlay" @click="closeLoginConfirm">
        <div class="login-confirm-dialog" @click.stop>
            <div class="login-confirm-content">
                <div class="login-confirm-title">您当前未登录</div>
                <div class="login-confirm-text">登录后才能使用该功能</div>
                <div class="login-confirm-buttons">
                    <button class="login-btn" @click="goToLogin">去登录</button>
                    <button class="cancel-btn" @click="closeLoginConfirm">再看看</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { defineComponent, ref, watch, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/user';


export default defineComponent({
    name: 'TabBar',
    setup() {
        const userStore = useUserStore();
        const router = useRouter();
        const route = useRoute();
        const active = ref(0);
        const showLoginConfirm = ref(false);
        const list = [
            {
                name: '/home',
                title: '首页',
                active: new URL('@/assets/images/nav_icon/home_select.png', import.meta.url).href,
                normal: new URL('@/assets/images/nav_icon/home.png', import.meta.url).href,
            },
            {
                name: '/chatAI',
                title: 'AI医生',
                active: new URL('@/assets/images/nav_icon/search_select.png', import.meta.url).href,
                normal: new URL('@/assets/images/nav_icon/search.png', import.meta.url).href,
            },
            {
                name: '/petStore',
                title: '宠物商城',
                active: new URL('@/assets/images/nav_icon/chat_select.png', import.meta.url).href,
                normal: new URL('@/assets/images/nav_icon/chat.png', import.meta.url).href,
            },
            {
                name: '/community',
                title: '猫咪社区',
                active: new URL('@/assets/images/nav_icon/mine_select.png', import.meta.url).href,
                normal: new URL('@/assets/images/nav_icon/mine.png', import.meta.url).href,
            },
        ];

        // 关闭登录确认弹窗
        const closeLoginConfirm = () => {
            showLoginConfirm.value = false;
        };

        // 去登录
        const goToLogin = () => {
            router.push({ path: "/login" });
            closeLoginConfirm();
        };
        // 根据当前路由自动设置活动项
        const updateActiveByRoute = () => {
            const currentPath = route.path;

            // 如果是搜索页面，不应该激活任何标签
            if (currentPath === '/search') {
                active.value = -1; // 使用-1表示没有选中任何标签
                return;
            }

            const index = list.findIndex(item => currentPath.startsWith(item.name));
            if (index !== -1) {
                active.value = index;
            }
        };

        // 监听路由变化
        watch(() => route.path, () => {
            updateActiveByRoute();
        });

        // 首次加载时设置active值
        onMounted(() => {
            updateActiveByRoute();
        });

        // 判断是否应该使用路由导航
        const shouldRoute = (index) => {
            // 如果是AI医生选项(index=1)，且用户未登录，则不使用路由
            if (index === 1) {
                try {
                    return userStore.token && userStore.userInfo && userStore.userInfo.id;
                } catch (error) {
                    console.error('检查用户状态出错:', error);
                    return false;
                }
            }
            return true; // 其他选项正常使用路由
        };

        const onChange = (index) => {
            // 如果点击的是AI医生选项，需要先检查登录状态
            if (index == 1) {
                try {
                    if (!userStore.token || !userStore.userInfo || !userStore.userInfo.id) {
                        showLoginConfirm.value = true;
                        // 不更新active状态，恢复为原来的状态
                        setTimeout(() => {
                            updateActiveByRoute(); // 重新根据当前路由设置active值
                        }, 0);
                        return;
                    }
                } catch (error) {
                    console.error('AI医生点击处理错误:', error);
                    router.push('/login');
                    return;
                }
            }
            
            // 只有通过验证才更新active值
            active.value = index;
        };

        const search = () => {
            router.push('/search');
            // 点击搜索按钮时，将active设为-1表示不选中任何标签
            active.value = -1;
        };

        return {
            active,
            list,
            onChange,
            shouldRoute,
            search,
            showLoginConfirm,
            closeLoginConfirm,
            goToLogin
        };
    },
});
</script>

<style lang="scss" scoped>
.van-tabbar {
    height: 60px !important;
    border: 1px solid #e5e5e5;
}

.van-tabbar-item__icon>img {
    width: 21px;
    height: 21px;
}

.van-tabbar-item:nth-child(2) {
    padding-right: 30px;
}

.van-tabbar-item:nth-child(3) {
    padding-left: 30px;
}

.circle-image-container {
    position: absolute;
    z-index: 999;
    bottom: 66%;
    left: 50%;
    transform: translate(-50%, 50%);
    width: 100px;
    height: 80px;
    overflow: hidden;
    background: transparent !important;
}

.circle-image-container img {
    width: 80px;
    height: 100%;
    margin-left: 10px;
    object-fit: cover;
}

.login-confirm-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
}

.login-confirm-dialog {
    width: 80%;
    max-width: 300px;
    background-color: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.login-confirm-content {
    padding: 20px;
}

.login-confirm-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
    text-align: center;
    color: #333;
}

.login-confirm-text {
    font-size: 14px;
    margin-bottom: 20px;
    text-align: center;
    color: #666;
}

.login-confirm-buttons {
    display: flex;
    justify-content: space-between;
}

.login-btn {
    flex: 1;
    margin-right: 10px;
    padding: 10px 0;
    background-color: #c6caa4;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: bold;
    cursor: pointer;
}

.cancel-btn {
    flex: 1;
    padding: 10px 0;
    background-color: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
}
</style>
